﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WpfRcp.Core.Views.Presenters;
using Microsoft.Practices.Composite.Presentation.Commands;
using WpfRcp.Core.Threading;
using Microsoft.Practices.ServiceLocation;
using WpfRcp.Core.Views;
using WpfRcp.Core.Services;
using WpfRcp.Modules.Panels.Properties;
using System.Threading;

namespace WpfRcp.Modules.Panels.Views.Presenters
{
    public class ToolbarPresentationModel : PresenterBase<IToolbarView>
    {
        public DelegateCommand<object> OpenAndDisplayFileCommand { get; set; }
        public DelegateCommand<object> WaitCommand { get; private set; }
        private readonly IContainerFacade m_Container;

        FirstTabPresentationModel m_model;

        public ToolbarPresentationModel(IToolbarView toolbarView, FirstTabPresentationModel model, IContainerFacade container)
        {
            View = toolbarView;
            View.Model = this;

            m_model = model;
            m_Container = container;

            OpenAndDisplayFileCommand = m_model.OpenAndDisplayFileCommand;
            WaitCommand = new DelegateCommand<object>(ExecuteWaitCommand);
        }

        private bool CanStop = false;
        private void Wait(object state)
        {
            for (int i = 0; i < 20; i++)
            {
                Thread.Sleep(1000);
                if (CanStop)
                {
                    break;
                }
            }
            CanStop = false;
            
        }

        private void ExecuteWaitCommand(object p)
        {
            var job = new Job(Wait, Resources.WaitJobName, new JobOptions(true, true));
            var progressView = m_Container.Resolve<IWindowedProgressView>();
            IShell shell = m_Container.Resolve<IShell>();
            progressView.OwnerView = shell;
            var statusManager = m_Container.Resolve<IStatusManager>();
            var monitor = statusManager.CreateSimpleStatusMonitor(Resources.WaitJobName, job, progressView);

            job.Error += (s, e) =>
            {
                // Show warning message
                var messageBox = m_Container.Resolve<IMessageBox>();
                messageBox.Show(Resources.Error, Resources.JobFailed,
                    MessageBoxViewButtons.OK, MessageBoxViewIcons.Error);
            };
            job.Completed += (s, e) => ShowJobEnd();
            job.Cancelled += (s, e) => { CanStop = true; ShowJobEnd(); };
            job.RunAsync();
            progressView.ShowDialog();
        }

        private void ShowJobEnd()
        {
            // Show warning message
            var messageBox = m_Container.Resolve<IMessageBox>();
            messageBox.Show(Resources.JobEnded, Resources.JobEnded,
                MessageBoxViewButtons.OK, MessageBoxViewIcons.Done);
            CanStop = false; 
        }

    }
}
